import { Token } from "service/token.js";
var u = require("/utils/util.js"), h = require("/utils/http.js"), a = require("/utils/api.js"),
o = require("/utils/onfire.js");

App({
  onLaunch: function (e) {     
    var t = this;
    t.globalData.launchOptions = e, 
    wx.getSystemInfo({
      success: function (e) {
        t.globalData.systemInfo = e;
      }
    })
    // wx.getLocation({
    //   success: function (e) {
    //     t.globalData.locationInfo = e;
    //     o.fire("location", e);
    //   }
    // });     
  },
  onShow: function () {    
    console.log('show--------------');
  },
  globalData: {    
    authentication:null,
    userInfo: null,
    locationInfo: null,
    systemInfo: {} 
  },  
  require: require,
  getToken:function(){
    var token = new Token();
    var old_time = wx.getStorageSync('keys_time');//旧的时间戳
    var keys_expire = 7000;//有效时间
    var now_time = new Date().getTime();
    if (!old_time || !keys_expire || (now_time - old_time > keys_expire * 1000)) {
      //获取token
      token.getTokenFromServer();    
    }
  },
  login: function (fun) {    
    var t = this;
    var n = function(n){
      var data = {code:n};
      h.noLoadReq('login/authorization',data,'POST',function(res){
        if (res.code == 0) {
          t.getUserInfo(res.data.key,fun);
        }   
      });
    }
    wx.login({
      success: function (e) {        
        n(e.code);
      }
    });
  },

  getUserInfo:function(key,fun){
    var t = this;
    wx.getUserInfo({
      success: function (n) {
        var data = {
          store_id: a.storeId,
          encryptedData: encodeURI(n.encryptedData),
          iv: encodeURI(n.iv),
          key: key,
            store_id:a.storeId
        };
        h.noLoadReq('login/login', data, 'POST', function (res) {
          if (res.code == 0) {
            t.globalData.userInfo = res.data,
            wx.setStorageSync('userInfo', res.data),
            o.fire("userInfo", res.data);
            return typeof fun == "function" && fun(res.data)
          }
        });    
      }
    });  
  },

  callAuthorize: function (fun) {
    var t = this, n = t.globalData.userInfo;
    // n && (n.nickname || n.avatar) && e.setData({
    //   dialogType: null
    // });
    wx.getSetting({
      success: function (a) {
        a.authSetting["scope.userInfo"] ? t.login(fun) : t.doLogin();        
      }
    });
  },
  doLogin: function () {
    let pages = getCurrentPages();
    if (pages.length) {
      let currentPage = pages[pages.length - 1];
      "pages/login/login" != currentPage.route &&
        wx.setStorageSync("currentPage", currentPage);
    }
    // 跳转授权页面
    wx.navigateTo({
      url: "/pages/login/login"
    });
  },

});